# -*- coding: UTF-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import numpy as np

file_path = "ruoyi-admin/src/main/java/com/ruoyi/business/seaTotal/pydos/异常-PC1系数.xlsx"
df = pd.read_excel(file_path)
df['Date'] = pd.to_datetime(df['Date'])

start_date = '2003-01'
end_date = '2023-12'
df_filtered = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)]
correlation = df_filtered['PC1'].corr(df_filtered['means-SSTA'])
print(f"PC1与means-SSTA的相关性: {correlation:.2f}")

# 使用行索引作为横坐标，计算PC1的线性趋势
index = np.arange(1, len(df_filtered) + 1)  # 从1开始编号
slope_pc1, intercept_pc1 = np.polyfit(index, df_filtered['PC1'], 1)
slope_ssta, intercept_ssta = np.polyfit(index, df_filtered['means-SSTA'], 1)
print(f"PC1的线性方程: y = {slope_pc1:.4f} * x + {intercept_pc1:.4f}")
print(f"means-SSTA的线性方程: y = {slope_ssta:.4f} * x + {intercept_ssta:.4f}")


plt.figure(figsize=(12, 6))
plt.plot(df_filtered['Date'], df_filtered['PC1'], label='PC1', color='blue')
plt.plot(df_filtered['Date'], df_filtered['means-SSTA'], label='means-SSTA', color='red')
plt.title('PC1 and Means-SSTA')
plt.xlabel('Date')
plt.ylabel('Values')
plt.xlim(pd.Timestamp('2003-01-01'), pd.Timestamp('2024-01-01'))
plt.xticks(pd.date_range(start='2003-01-01', end='2024-01-01', freq='YS'))
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.legend()
plt.tight_layout()
'''
save_path = r"F:/北黄海0.01°再分析/EOF/PC1_and_Means_SSTA_with_Trend.png"
plt.savefig(save_path, dpi=300)
'''
plt.show()
